#!/usr/bin/env python
# -*- encoding: utf-8 -*-


import re

from .sqlitebase import SQLiteMixin, SplitTableMixin
from pyspider.database.base.groupdb import GroupDB as BaseGroupDB
from pyspider.database.basedb import BaseDB


class GroupDB(SQLiteMixin, SplitTableMixin, BaseGroupDB, BaseDB):
    __tablename__ = 'groupdb'
    placeholder = '?'

    def __init__(self, path):
        self.path = path
        self.last_pid = 0
        self.conn = None
        self._list_project()

    def _create_project(self, project):
        assert re.match(r'^\w+$', project) is not None
        tablename = self._tablename(project)
        self._execute('''CREATE TABLE IF NOT EXISTS `%s` (
                group_keyword,
                resultid,
                title,
                url
                )''' % tablename)

    def save(self, group_keyword, resultid, title, url):
        project = resultid.split(':')[0]
        tablename = self._tablename(project)
        self._list_project()
        if project not in self.projects:
            self._create_project(project)
            self._list_project()
        obj = {
            'group_keyword': group_keyword,
            'resultid': resultid,
            'title': title,
            'url': url,
        }
        return self._replace(tablename, **obj)
